<template>
  <div class="user-edit">
    <!-- Drawer抽屉 -->
    <Drawer :title="title" v-model="visible" width="1400" :mask-closable="false">
      <Scroll :height="height">
        <Card style="width:96%;margin-left: 2%">
          <p slot="title">
            <b>{{typicalDesign.typical_name}}</b>&nbsp;&nbsp; [ {{typicalDesign.pole_type}} ]
          </p>
          <Row :gutter="16">
            <Col span="9">
              <p class="listTitle">基&nbsp;础&nbsp;信&nbsp;息</p></br>
              <Form ref="typicalDesign" :model="typicalDesign" :label-width="100"
                    style="width: 90%;font-size: 12px;">
                <FormItem label="典型设计类型" prop="typical_classification_id">
                  <Select v-model="typicalDesign.typical_classification_id">
                    <Option v-for="item in typicalClassList" :value="item.id" :key="item.id">
                        {{item.classification_name}}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem label="设计序号" prop="serial_number" >
                  <Input v-model="typicalDesign.serial_number"/>
                </FormItem>
                <FormItem label="排序" prop="sort_order" >
                  <Input v-model="typicalDesign.sort_order"/>
                </FormItem>
                <FormItem label="典型设计名称" prop="typical_name">
                  <Input v-model="typicalDesign.typical_name"/>
                </FormItem>
                <FormItem label="杆型" prop="pole_type">
                  <Input v-model="typicalDesign.pole_type"/>
                </FormItem>
                <FormItem label="杆径与杆高" prop="pole_highly">
                  <Input v-model="typicalDesign.pole_highly"/>
                </FormItem>
                <FormItem label="适用范围" prop="apply_scope">
                  <Input v-model="typicalDesign.apply_scope"/>
                </FormItem>
                <FormItem label="材料表说明" prop="description">
                  <Input v-model="typicalDesign.description" :title="typicalDesign.description"/>
                </FormItem>
                <FormItem label="图号" prop="figure_number">
                  <Input v-model="typicalDesign.figure_number"/>
                </FormItem>
                <FormItem label="示例图" prop="typical_figure_path">
                  <img :src="baseUrl + '\/public\/uploads\/' + typicalDesign.typical_figure_path" alt="" width="90%"
                      style="width: 64px;"
                      @click="handleView(typicalDesign.typical_figure_path)">
                </FormItem>
              </Form>
            </Col>
            <Col span="15">
              <p class="listTitle">设&nbsp;备&nbsp;材&nbsp;料&nbsp;表</p>
              <table width="98%" class="gridtable">
                <tr>
                  <th>序号</th>
                  <th>材料编码</th>
                  <th>材料名称</th>
                  <th>材料规格</th>
                  <th>单位</th>
                  <th width="100">数量</th>
                  <th witdh="200">操作</th>
                </tr>
                <tr v-for="(item,index) in typicalMaterial" :key="index">
                  <td style="text-align: center">
                    {{index+1}}<i style="color: red;display: none">{{item.id}}</i>
                  </td>
                  <td style="text-align: center">
                    {{item.code}}
                  </td>
                  <td>{{item.name}}<i style="color: red;display: none">{{item.material_id}}</i></td>
                  <td>{{item.stype}}</td>
                  <td style="text-align: center">{{item.unit}}</td>
                  <td style="text-align: center">
                    <Button type="primary" size="small" @click="handle_sub(index)">-</Button>
                    <input type="text" v-model="item.count" style="width: 30px;text-align: center;"
                              readonly="readonly">
                    <Button type="primary" size="small" @click="handle_add(index)">+</Button>
                  </td>
                  <td style="text-align: center">
                    <Button type="text" size="small" @click="handle_edit_material(index)">编辑</Button>
                    <Button type="text" size="small" @click="handle_del(index)">删除</Button>
                  </td>
                </tr>
              </table>
              <br>
              <Button
                icon="ios-download-outline"
                type="primary"
                style="margin-left: 20px;"
                @click="handle_add_material">
                新增材料
              </Button>
            </Col>
          </Row>
        </Card>
      </Scroll>
      <div class="demo-drawer-footer">
        <Button @click="cancel" style="margin-right:32px">取消</Button>
        <Button type="primary" @click="submit">确定</Button>
      </div>
    </Drawer>
    <Modal title="图片预览" v-model="viewImage" width="40%">
      <img :src="imgUrl" style="width: 94%;margin: 0 auto;display: block;">
    </Modal>
    <Modal
      v-model="show_edit_add_material"
      scrollable
      :title="op_material_title"
      class-name="vertical-center-modal"
      :styles="{top: '250px'}"
      @on-ok="handle_ok">
      <p class="rowmargin">
        物料名称
        <Select v-model="material_name" filterable clearable style="width: 320px;" @on-change="changeMaterialName">
          <Option v-for="item in materialClass"
                :value="item.pre_code"
                :key="item.pre_code">
            {{ item.name }}
          </Option>
        </Select>
      </p>
      <p class="rowmargin">
        规格型号
        <Select v-model="material_type" filterable style="width: 320px;" @on-change="changeMaterialId">
          <Option v-for="item in materialType"
                :value="item.id"
                :key="item.id">
            {{ item.stype }}
          </Option>
        </Select>
      </p>
      <p class="rowmargin">
          　　物料数量
          <InputNumber v-model="current_material.count" style="width: 320px"></InputNumber>
      </p>
    </Modal>
  </div>
</template>

<script>
import { base_url } from '@/libs/axios';
import { getTypicalClassification, deleteTypicalMaterial, getAllMaterialName, getTypicalMaterials,
         getAllMaterials, getMaterialById, insertTypicalMaterial, updateTypicalMaterial, 
         deleteSysTypicalMaterial, insertSysTypicalMaterial, getSysTypicalMaterials, updateSysTypicalMaterial,
         getSysTypicalClass, getMyTypicalClass, updateTypicalDesign, updateSysTypicalDesign } from '@/api/typical';
export default {
  name: "editTypical",
  components: {
    
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    typicalDesign: Object,
    typicalMaterial: Array,
    typicalClassList: Array,
    type: {
      /**
       * '1': 官方典型设计
       * '2': 系统典型设计
       * '3': 自定义典型设计
       */
      type: String,
      default: "0"
    }
  },
  data() {
    return {
      visible: this.value,
      title: "编辑典型设计详情",
      baseUrl: base_url,
      height: 540,
      typicalClassList: [],
      imgUrl: '',
      viewImage: false,
      // add_material_type 为true表示是新增物料操作，为false表示是编辑物料操作
      add_material_type: false,
      show_edit_add_material: false,
      materialType: [],
      material_type: '',
      materialLib: [],
      materialClass: [],
      current_typical_id: 0,
      material_name: '',
      op_material_title: '',
      current_material: {
        index: null,
        id: null,
        typical_design_id: 0,
        material_id: 0,
        code: '',
        name: '',
        stype: '',
        unit: '',
        count: null
      },
    };
  },
  methods: {
    // getTypicalClass() {
    //   getTypicalClassification().then(res => {
    //     if (res.code === 0) {
    //       this.typicalClassList = res.data;
    //     }
    //   })
    // },
    // getSysTypicalClasses() {
    //   console.log('typicalDesign-------', this.typicalDesign)
    //   if (this.typicalDesign.sys_or_local == 1) {
    //     getSysTypicalClass().then(res => {
    //       if (res.code === 0) {
    //         this.typicalClassList = res.data;
    //       }
    //     })
    //   } else if (this.typicalDesign.sys_or_local == 2) {
    //     getMyTypicalClass().then(res => {
    //       if (res.code === 0) {
    //         this.typicalClassList = res.data;
    //       }
    //     })
    //   }
      
    // },
    init() {
      // switch(this.type) {
      //   case '1':
      //     this.getTypicalClass();
      //     break;
      //   case '2':
      //     this.getSysTypicalClasses();
      //     break;
      // }
      
      this.getMaterialInfo();
      this.current_typical_id = this.typicalDesign.id;
    },
    handleView(imgUrl) {
      this.imgUrl = this.baseUrl + '\/public\/uploads\/' + imgUrl;
      this.viewImage = true;
    },
    // 数量变化写数据
    change_count(index) {
      let params = {};
      params.id = this.typicalMaterial[index].id;
      params.count = this.typicalMaterial[index].count;
      switch(this.type) {
        case '1':
          updateTypicalMaterial(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
            }
          })
          break;
        case '2':
          updateSysTypicalMaterial(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
            }
          })
          break;
      }
    },
    // 数量减一按钮
    handle_sub(index) {
      if (this.typicalMaterial[index].count == 1) {
        return;
      } else {
        this.typicalMaterial[index].count--;
      }
      this.change_count(index);
    },
    // 数量加一按钮
    handle_add(index) {
      this.typicalMaterial[index].count++;
      this.change_count(index);
    },
    handle_edit_material(index) {
      this.add_material_type = false;
      this.current_material.material_id = this.typicalMaterial[index].material_id;
      this.show_material_modal(index);
    },
    show_material_modal(index) {
      this.current_material.typical_design_id = this.typicalDesign.id;
      if (this.add_material_type) {
        this.op_material_title = '新增材料';
        this.material_name = '';
        this.material_type = '';
        this.current_material.count = 1;
      } else {
        this.op_material_title = '编辑材料';
        this.current_material.index = index;
        this.current_material.id = this.typicalMaterial[index].id;
        this.current_material.code = this.typicalMaterial[index].code;
        this.current_material.name = this.typicalMaterial[index].name;
        this.current_material.stype = this.typicalMaterial[index].stype;
        this.current_material.unit = this.typicalMaterial[index].unit;
        // 取物料的base_code
        this.material_name = this.typicalMaterial[index].code.substring(0, 6);
        this.material_type = this.typicalMaterial[index].material_id;
        this.current_material.count = this.typicalMaterial[index].count;
        this.changeMaterialName(this.material_name);
      }
      this.show_edit_add_material = true;
    },
    getMaterialInfo() {
      // 获取所有的物料名称
      getAllMaterialName().then(res => {
        if (res.code === 0) {
          this.materialClass = res.data.raws;
        }
      });
      // 获取所有的物料
      getAllMaterials().then(res => {
        if (res.code === 0) {
          this.materialLib = res.data.rows;
        }
      })
    },
    // 物料过滤得到特定名称的所有类型
    changeMaterialName(value) {
      this.materialType = this.materialLib.filter(item => item.base_code == value);
    },
    // 按物料id获取物料的详情
    changeMaterialId(value) {
      if (value) {
        getMaterialById({id: value}).then(res => {
          if (res.code === 0) {
            this.current_material.material_id = res.data.id;
            this.current_material.code = res.data.code;
            this.current_material.name = res.data.name;
            this.current_material.stype = res.data.stype;
            this.current_material.unit = res.data.unit;
            this.current_material.typical_design_id = this.current_typical_id;
          }
        })
      }
    },
    handle_del(index) {
      this.$Modal.confirm({
        title: '确定删除',
        content: '确定要删除这条记录吗？',
        onOk: () => {
          let params = {};
          params.id = this.typicalMaterial[index].id;
          switch(this.type) {
            case '1':
              deleteTypicalMaterial(params).then(res => {
                this.typicalMaterial.splice(index, 1);
                this.$Message.success(res.message);
              });
              break;
            case '2':
              deleteSysTypicalMaterial(params).then(res => {
                this.typicalMaterial.splice(index, 1);
                this.$Message.success(res.message);
              })
              break;
          }
          
        }
      });
    },
    handle_add_material() {
      this.add_material_type = true;
      this.show_material_modal();
    },
    handle_ok() {
      if (this.add_material_type) { // 新增物料
        let params = {};
        params.typical_design_id = this.typicalDesign.id;
        params.material_id = this.current_material.material_id;
        params.count = this.current_material.count;
        console.log('params:', params);
        switch(this.type) {
          case '1':
            insertTypicalMaterial(params).then(res => {
              if (res.code === 0) {
                this.$Message.success(res.message);
                getTypicalMaterials({typical_design_id:this.typicalDesign.id}).then(res => {
                  this.typicalMaterial = res.data.raws;
                });
              }
            })
            break;
          case '2':
            console.log('params2:', params);
            insertSysTypicalMaterial(params).then(res => {
              if (res.code === 0) {
                this.$Message.success(res.message);
                getSysTypicalMaterials({typical_design_id:this.typicalDesign.id}).then(res => {
                  this.typicalMaterial = res.data;
                });
              }
            })
            break;
        }
      } else {  //编辑物料
        let params = {};
        params.id = this.current_material.id;
        params.material_id = this.current_material.material_id;
        params.count = this.current_material.count;
        params.typical_design_id = this.typicalDesign.id;  
        switch(this.type) {
          case '1':
            updateTypicalMaterial(params).then(res => {
              if (res.code === 0) {
                this.$Message.success(res.message);
                getTypicalMaterials({typical_design_id:this.typicalDesign.id}).then(res => {
                  this.typicalMaterial = res.data.raws;
                });
              }
            });
            break;
          case '2':
            updateSysTypicalMaterial(params).then(res => {
              if (res.code === 0) {
                this.$Message.success(res.message);
                getSysTypicalMaterials({typical_design_id:this.typicalDesign.id}).then(res => {
                  this.typicalMaterial = res.data;
                });
              }
            })
            break;
        }   
            
      }
    },
    cancel() {
      this.visible = false;
    },
    submit() {
      switch(this.type) {
        case '1':
          updateTypicalDesign(this.typicalDesign).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message)
            }
          });
          break;
        case '2':
          updateSysTypicalDesign(this.typicalDesign).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message)
            }
          });
          break;
      }
      this.visible = false;
    },
    setCurrentValue(value) {
      this.visible = value;
    }
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.$emit("input", value);
    }
  },
  mounted() {
    this.height = Number(document.documentElement.clientHeight - 100);
    this.init();
  }
};
</script>

<style lang="less">
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.listTitle {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}
table.gridtable {
  font-family: verdana, arial, sans-serif;
  font-size: 12px;
  color: #777777;
  border-width: 1px;
  border-color: #777777;
  border-collapse: collapse;
}

table.gridtable th {
  border-width: 1px;
  padding: 6px;
  border-style: solid;
  border-color: #aaaaaa;
  background-color: #dedede;
}

table.gridtable td {
  border-width: 1px;
  padding: 4px;
  border-style: solid;
  border-color: #8b8b8b;
  background-color: #ffffff;
}
</style>

